﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using ZLCMS.Data.Model;
using ZLCMS.Data.Common;
using NHibernate.Criterion;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Web.SystemManage.Basics.ProductSKU;
using System.Collections.Generic;
using ZLCMS.Business.Shop.Data;


namespace ZLCMS.Web.SystemManage.Basics
{
    public partial class SkuOrderView : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        protected ShopOrderInfo _ordersDB;//当前订单信息
        protected ShopShippingInfo _shippingDB;//当前配送方式
        protected ShopPaymentInfo _paymentDB;//当前付费方式
        protected MemberInfo _ordersMemberDB;//当前订单购买会员信息
        protected string _owner;
        protected int ShippingCount { get; set; }
        protected string _userAccount;
        protected decimal _hxffje
        {
            get
            {
                return _ordersDB.TotalPrice - _ordersDB.UseAdvancePayment;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            //初始化DWZ控件
            _framePage = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();

            
            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        #region 初始化全局变量 + protected void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        protected void InitializeGlobalValue()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (!IsPostBack)
                    {
                        _id.Text = Request["uid"];
                        _freshtabid.Text = String.IsNullOrEmpty(Request["freshtabid"]) ? _framePage.NavTabId : Request["freshtabid"];
                        _owner = UserKit.GetUserAccountFailLogin();
                    }

                    _ordersDB = session.Get<ShopOrderInfo>(int.Parse(_id.Text));

                    if (_ordersDB == null)
                    {
                        throw new Exception("找不到对应信息.");
                    }

                    _shippingDB = session.Get<ShopShippingInfo>(int.Parse(_ordersDB.ShippingType));

                    if (_shippingDB == null)
                    {
                        _shippingDB = new ShopShippingInfo();
                    }
                    if (!IsPostBack)
                    {
                        JGridControl2.Value = _ordersDB.ShippingNo;
                    }
                    _paymentDB = session.Get<ShopPaymentInfo>(int.Parse(_ordersDB.PaymentType));

                    if (_paymentDB == null)
                    {
                        _paymentDB = new ShopPaymentInfo();
                    }

                    _ordersMemberDB = session.CreateCriteria<MemberInfo>().Add(Expression.Eq("AccountId", _ordersDB.MemberAccount)).Add(Expression.Eq("OwnerAccount", _owner)).UniqueResult<MemberInfo>();

                    if (_ordersMemberDB == null)
                    {
                        _ordersMemberDB = new MemberInfo();
                    }
                    String hql = "from ShopOrderProduct o, ShopProductInfo p,ShopSkuProduct s where p.ProductNo = o.ProductNo and o.OrderNo = '" + _ordersDB.OrderNo + "' and s.ProductSkuCode=o.SkuProductNo";
                    IQuery query = session.CreateQuery(hql);
                    grid.DataSource = query.List();
                    grid.DataBind();
                    string couponSql = "from ShopSpecialPrice where OrderNo=:oid ";
                    rpt_couponlist.DataSource = session.CreateQuery(couponSql).SetParameter("oid",_ordersDB.OrderNo).List();
                    rpt_couponlist.DataBind();
                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }
        } 
        #endregion

        #region 初始化页面内容 + protected void InitializeContent()
        /// <summary>
        /// 初始化页面内容
        /// </summary>
        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                //页面控件数据

                //ParamKit.Bind("FaHuoZhe", ddl_fh, null, null, null, "-1", "-1");
                //ddl_fh.SelectedValue = _ordersDB.Fh.HasValue ? _ordersDB.Fh.Value.ToString() : "-1";

                JGridControl2.Columns.Add(new ListItem() { Text = "快递单号", Value = "ShippingNo" });
                JGridControl2.Columns.Add(new ListItem() { Text = "商品名称", Value = "ProductName" });
                JGridControl2.Columns.Add(new ListItem() { Text = "SKU编号", Value = "ProductSkuNo" });
                JGridControl2.Columns.Add(new ListItem() { Text = "快递公司名称", Value = "ShippingComName" });
                JGridControl2.Columns.Add(new ListItem() { Text = "快递公司编码", Value = "ShippingComNo" });
                JGridControl2.Columns.Add(new ListItem() { Text = "备注", Value = "Memo" });
                JGridControl2.EditorUrl = "/SystemManage/Basics/SkuOrderInfo/SkuOrderSendGoods.aspx?uid="+_ordersDB.OrderNo ;
                JGridControl2.OptionExt = "<a href='http://www.kuaidi100.com/chaxun?com={ShippingComNo}&nu={ShippingNo}' target='_blank'>查物流</a>&nbsp;&nbsp;<a href='/Systemmanage/Basics/Shop/PrintConfig/PrintDemo.aspx?uid=" + _ordersDB.Id + "' target='_blank'>打印</a>";
                if (_ordersDB.ShippingStatus == "1")
                {
                    JGridControl2.Readonly = true;
                }
                else
                {
                    JGridControl2.Readonly = AuthorizationKit.GetInstance().GetAuthorizationValue("ORDER", "EDIT_SHIPPING") == 0;
                }

                try
                {
                    if (JGridControl2.Value != null)
                    {
                        ShippingCount = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<ShippingItem>>(JGridControl2.Value).Count();
                    }
                    else
                    {
                        ShippingCount = 0;
                    }
                }
                catch (System.Exception ex)
                {
                    ShippingCount = 0;
                }
            }
        } 
        #endregion
        protected string ShowSkuItem(object o)
        {
            if (o == null)
                return "";
            using (var session = SessionFactoryHelper.CreateSession())
            {
                string str = "";
                List<SKUGroup> groups = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SKUGroup>>(o.ToString());
                if (groups == null)
                    return str;
                foreach (var item in groups)
                {
                    str += item.GroupName + ": " + session.Get<ShopSkuItem>(item.ItemId).ItemName + "&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                return str;
            }
        }
        #region 保存操作 + protected void Save()
        /// <summary>
        /// 保存操作
        /// </summary>
        protected void Save()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (!string.IsNullOrEmpty(tb_totalprice.Text))
                    {
                        _ordersDB.TotalPrice = decimal.Parse(tb_totalprice.Text);
                    }
                    _ordersDB.ShippingNo = JGridControl2.Value;
                    _ordersDB.ManageHistory += string.Format("<br><font color=red>【{0}】修改订单总金额，({1}){2}</font>", UserKit.GetUserAccount(), DateTime.Now, tb_glyfy.Text);

                    session.Update(_ordersDB);
                    session.Flush();
                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }
            _framePage.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                //callbackType = "closeCurrent",
                navTabId = "vieworder"
            });
        } 
        #endregion
    }
}
